<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页答题系统</title>
    <link th:href="@{/css/list.css}" rel="stylesheet"/>
    <script th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
    <!-- 左侧分类 -->
    <div id="category-nav">
        <div class="category-item active" data-category="math">数学题</div>
        <div class="category-item" data-category="history">历史题</div>
    </div>

    <!-- 右侧内容 -->
    <div id="main-content">
        <div id="questions-container"></div>
        <div class="load-more">加载中...</div>
    </div>

    <!-- 统计按钮和弹窗 -->
    <!-- <button id="toggle-stats">显示统计</button>
    <div class="stats-modal">
        <h3>答题统计</h3>
        <p>已答题数：<span id="total-answered">0</span></p>
        <p>正确数：<span id="correct-count">0</span></p>
        <p>正确率：<span id="accuracy">0</span>%</p>
    </div> -->

<script>
// 模拟分页数据
const mockData = {
    math: Array.from({length: 50}, (_, i) => ({
        type: i % 2 === 0 ? 'single' : 'multiple',
        question: `数学题 ${i + 1}`,
        options: { A: "选项A", B: "选项B", C: "选项C", D: "选项D" },
        answer: i % 2 === 0 ? 'B' : ['A', 'C'],
        explanation: `这是第 ${i + 1} 题的解析`
    })),
    history: Array.from({length: 30}, (_, i) => ({
        type: 'single',
        question: `历史题 ${i + 1}`,
        options: { A: "选项A", B: "选项B", C: "选项C" },
        answer: 'A',
        explanation: `历史题 ${i + 1} 解析`
    }))
};

let currentState = {
    category: 'math',
    page: 0,
    pageSize: 20,
	totalPage: 3,
    totalAnswered: 0,
    correctCount: 0,
    loading: false,
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
	loadCategory();
    //loadQuestions();
    setupEventListeners();
});

async function loadCategory(){
	$.post('/getType', (data)=>{
		const nav = $('#category-nav');
		nav.empty();
		nav.append('<div class="category-item " data-category="">全部</div>');
		nav.append('<div class="category-item " data-category="A">小题库</div>');
		data.map( (item,index) => {
			if(index == 0){
				currentState.category = item.dlType;
			}
			nav.append('<div class="category-item '+(index==0?' active ': '')+' " data-category="'+item.dlType+'">'+item.tkDl+'</div>')
		});
		loadQuestions();
	});
}

$('body').on('click', '.category-item', function(){
	 $('.category-item ').removeClass('active');
     $(this).addClass('active');
     currentState.category = $(this).attr('data-category');
     console.log(currentState.category);
     currentState.page = 0;
     $('#questions-container').html('');
     loadQuestions();
	 $('.load-more').css('display',  'block');
	 
	 currentState.totalAnswered = 0;
	 currentState.correctCount = 0;
	 $('#total-answered').text('0');
	 $('#correct-count').text('0');
	 $('#accuracy').text('0');
});


function setupEventListeners() {
    // 分类切换
    document.querySelectorAll('.category-item').forEach(item => {
        item.addEventListener('click', () => {
            document.querySelector('.category-item.active').classList.remove('active');
            item.classList.add('active');
            currentState.category = item.dataset.category;
            currentState.page = 0;
            document.getElementById('questions-container').innerHTML = '';
            loadQuestions();
			document.querySelector('.load-more').style.display = 'block';
        });
    });

    // 滚动加载
    document.getElementById('main-content').addEventListener('scroll', handleScroll);

    
}

// 加载题目
async function loadQuestions() {
    if (currentState.loading) return;
    currentState.loading = true;

    // 模拟异步加载
    setTimeout(() => {
        /* const data = mockData[currentState.category];
        const start = (currentState.page - 1) * currentState.pageSize;
        const end = start + currentState.pageSize;
        const pageData = data.slice(start, end);

        renderQuestions(pageData);
        currentState.page++;
        currentState.loading = false; */
        
        var curPage = currentState.page + 1;
        $.post('/getAsk',{current:curPage, limit: currentState.pageSize, dlType: currentState.category }, (data)=>{
        	currentState.page = curPage,
        	currentState.totalPage = data.pages;
        	currentState.loading = false;
        	renderQuestions(data.records);
        })
        
    }, 500);
}

function renderQuestions(questions) {
    const container = document.getElementById('questions-container');
    
    questions.forEach((q, i) => {
        const questionEl = document.createElement('div');
        const startNo = (currentState.page - 1) * currentState.pageSize + i + 1;
        let expl =  '';
        if(q.explanation){
        	expl = encodeURIComponent(q.explanation);
        }
        var answer = '';
        if(typeof(q.answer) != 'string' ){
        	answer = q.answer.join();
        }else{
        	answer = q.answer;
        }
        questionEl.className = 'question-card';
        var html = '<h3>'+startNo+'、'+q.question+'</h3>';
        var options = q.options;
        html += '<div class="options-container">';
        for(key in options){
        	html += '<label class="option-item '+(answer.indexOf(key)!=-1? 'correct' : '')+' ">' + key + '.' + options[key] + '</label>';
        }
        html += '</div>';
        html += '<div class="answer-info">';
        html += '<p>正确答案:'+answer+'</p>';
        html += '<p>解析:'+q.explanation+'</p>';
        html += '</div>';
        questionEl.innerHTML = html;
        
        container.appendChild(questionEl);
    });
}



// 滚动加载处理
function handleScroll() {
    const container = document.getElementById('main-content');
    const { scrollTop, scrollHeight, clientHeight } = container;
    console.log(scrollTop+'---'+ scrollHeight+'------'+clientHeight);
    if (scrollHeight - scrollTop - clientHeight < 100) {
		if(currentState.page > currentState.totalPage){
            document.querySelector('.load-more').style.display = 'none';
	    }else{
		   loadQuestions();
		}
    }
}
</script>
</body>
</html>